﻿using System;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Data;
using System.Net;
using System.Text;
using Matrix.Common.Utility;
using Matrix.MaKaYunShang.Model;
using Matrix.MaKaYunShang.DAL;
using Matrix.MaKaYunShang.Model.Enum;
using Matrix.MaKaYunShang.Model.MatrixCloudApi;
using Newtonsoft.Json;

namespace Matrix.MaKaYunShang.BLL
{
    public partial class SmsRecordBLL : BaseBLL<SmsRecordBLL>
    {
        private static readonly string SendMsgUrl = ConfigurationManager.AppSettings["SendMsgUrl"];
        private static readonly string SendMsgAccount = ConfigurationManager.AppSettings["SendMsgAccount"];
        private static readonly string SendMsgPwd = ConfigurationManager.AppSettings["SendMsgPwd"];
        private static readonly string SendMsgTitle = ConfigurationManager.AppSettings["SendMsgTitle"];

        #region 默认方法
        /// <summary>
        /// 增加一条数据
        /// </summary>
        public int Add(SmsRecord model)
        {
            return SmsRecordDAL.Instance.Add(model);
        }

        /// <summary>
        /// 更新一条数据
        /// </summary>
        public bool Update(SmsRecord model)
        {
            return SmsRecordDAL.Instance.Update(model);
        }

        /// <summary>
        /// 删除一条数据
        /// </summary>
        public bool Delete(int Id)
        {
            return SmsRecordDAL.Instance.Delete(Id);
        }
        /// <summary>
        /// 批量删除一批数据
        /// </summary>
        public bool DeleteList(string Idlist)
        {
            return SmsRecordDAL.Instance.DeleteList(Idlist);
        }

        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public SmsRecord GetModel(int Id)
        {
            var ds = SmsRecordDAL.Instance.GetModel(Id);
            return ds == null ? null : ServicesHelper.DataSetToIList<SmsRecord>(ds).ToList()[0];
        }

        /// <summary>
        /// 获得数据列表
        /// </summary>
        public List<SmsRecord> GetModelList(string strWhere = null)
        {
            var ds = SmsRecordDAL.Instance.GetList(strWhere);
            return ServicesHelper.DataSetToIList<SmsRecord>(ds).ToList();
        }
        #endregion

        #region 扩展方法

        /// <summary>
        /// 效验二维码是否可用
        /// </summary>
        /// <param name="mobile"></param>
        /// <param name="code"></param>
        /// <param name="userActionSource"></param>
        /// <returns></returns>
        public SmsRecord CheckCode(string mobile, string code, int userActionSource)
        {
            string sendCode = string.Empty;
            var smsRecord = GetModelByMobileOrCode(mobile, code, userActionSource);
            if (smsRecord != null && (smsRecord.SendSMSTime.AddMinutes(smsRecord.FailTime) > DateTime.Now))
            {
                return smsRecord;

            }
            return null;
        }
        public SmsRecord GetModelByMobileOrCode(string mobile, string code, int userActionSource)
        {
            DataSet ds = SmsRecordDAL.Instance.GetModelByMobileOrCode(mobile, code, userActionSource);
            return ds == null ? null : ServicesHelper.DataSetToIList<SmsRecord>(ds).ToList()[0];
        }
        public string utf8_gb2312(string text)
        {
            //声明字符集   
            System.Text.Encoding utf8, gb2312;
            //utf8   
            utf8 = System.Text.Encoding.GetEncoding("utf-8");
            //gb2312   
            gb2312 = System.Text.Encoding.GetEncoding("gb2312");
            byte[] utf;
            utf = utf8.GetBytes(text);
            utf = System.Text.Encoding.Convert(utf8, gb2312, utf);
            //返回转换后的字符   
            return gb2312.GetString(utf);
        }

        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="userId">用户id</param>
        /// <param name="mobile">手机</param>
        /// <param name="sendContent">发送内容</param>
        /// <param name="sendFrom"> 发送方平台</param>
        /// <param name="userActionSource"> 发送对象用户行为来源</param>
        /// <param name="code">验证码</param>
        /// <param name="failTime">多少分钟后失效</param>
        public bool SendSms(string mobile, string sendContent, CommonEnum.SmsRecordSendFrom sendFrom, CommonEnum.SmsRecordUserActionSource userActionSource, string code = null, int failTime = 0,int userId=0)
        {
            var smsRecordModel = new SmsRecord
            {
                WechantInfoId = 1,
                SendFrom = (int)sendFrom,
                SendContent = sendContent,
                SendCode = code,
                SendSMSTime = DateTime.Now,
                Mobile = mobile,
                UserActionSource = (int)userActionSource,
                FailTime = failTime,
                RequestUserId = userId
            };
            try
            {
                var result = string.Empty;
                try
                {
                    result = ClientHelper.GetWebContent(string.Format(SendMsgUrl, mobile, System.Web.HttpUtility.UrlEncode(sendContent, System.Text.Encoding.GetEncoding("gb2312"))));
                    if (result != "1")
                    {
                        return false;
                    }
                }
                catch (Exception ex)
                {
                    _fileLog.Error("SmsRecordBLL | SendSMS | Exception: " + ex.Message);
                }
                if (!string.IsNullOrEmpty(result))
                {
                    smsRecordModel.SmsSerialNumber = "";
                    smsRecordModel.SentResult = result;
                }
                Add(smsRecordModel);
            }
            catch (Exception ex)
            {
                _fileLog.Error("SmsRecordBLL | SendSMS | Exception: " + ex.Message);
            }
            return true;
        }

        #endregion
    }

    /// <summary>
    /// 短信接口返回数据
    /// </summary>
    public class SmsResult
    {
        public string rspmsg { get; set; }
        public int rspcode { get; set; }
        public int apiver { get; set; }
        public List<SmsResultMsgid> data { get; set; }
    }

    public class SmsResultMsgid
    {
        public string msgid { get; set; }
    }
}